package com.talent.jiwen.teacher;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.adapter.CourseListAdapter;
import com.talent.jiwen.base.BaseFragment;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.OrderResult;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import rx.Observable;

/**未接课程列表
 *
 */
public class CourseListFragment extends BaseFragment {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    List<OrderResult.Order> courseList = new ArrayList<>();
    private CourseListAdapter courseListAdapter;
    private Handler handler;
    private TimeRunnable timeRunnable;
    private Thread timeThread;

    public static final String REFRESH_COURSE_LIST = "refresh.course.list";
    private static int NOTIFY_TIME = 1;

    @Override
    protected void initData() {

        registEventBus();

        noDataIv.setImageResource(R.mipmap.img_no_course);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == NOTIFY_TIME){
                    if(!Validators.isEmpty(courseList)){
                        courseListAdapter.notifyData();
                    }
                }
                super.handleMessage(msg);
            }
        };
        timeRunnable = new TimeRunnable();
        timeThread = new Thread(timeRunnable);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recycleView.setLayoutManager(linearLayoutManager);
        courseListAdapter = new CourseListAdapter(getActivity() , courseList);
        recycleView.setAdapter(courseListAdapter);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();

    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_COURSE_LIST)){
            refreshLayout.autoRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
//        handler.removeCallbacks(timeRunnable);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_course_list;
    }

    class TimeRunnable implements  Runnable{
        boolean endThread;

        @Override
        public void run() {
            while (!endThread) {
                try {

                    Thread.sleep(1000);

                    for (OrderResult.Order order : courseList) {

                        int time = (int)((new Date().getTime() - order.getCreateTime()) / 1000);
                        String timeFormat;
                        String min = new DecimalFormat("00").format(time / 60);
                        if (Integer.parseInt(min) < 60){
                            String mm = new DecimalFormat("00").format(time / 60);
                            String ss = new DecimalFormat("00").format(time % 60);
                            timeFormat = new String( mm + ":" + ss);
                        }else{
                            String hh = new DecimalFormat("00").format(time / 3600);
                            String mm = new DecimalFormat("00").format(time % 3600 / 60);
                            String ss = new DecimalFormat("00").format(time % 60);
                            timeFormat = new String( hh + ":" + mm + ":" + ss);
                        }

                        order.setChangeTime(timeFormat);
                    }

                    Message msg = new Message();
                    msg.what = NOTIFY_TIME;
                    handler.sendMessage(msg);

                } catch (Exception e) {

                }
            }
        }
    }

    /**获取订单列表
     *
     */
    private void getOrderList(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getOriginalOrder(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderResult>(getActivity()) {
            @Override
            protected void _onNext(OrderResult orderResult) {
                courseList.clear();
                courseList.addAll(orderResult.getOrderList());
                recycleView.getAdapter().notifyDataSetChanged();

                refreshLayout.finishRefresh();

//                handler.post(timeRunnable);
                if (!Validators.isEmpty(courseList)){
                    if (!timeThread.isAlive()){
                        timeThread.start();
                    }

                    noDataIv.setVisibility(View.GONE);
                }else{
                    noDataIv.setVisibility(View.VISIBLE);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);

                if (null != refreshLayout){
                    refreshLayout.finishRefresh();
                }
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

//     recycleView.setAdapter(new CommonAdapter<OrderResult.Order>(getContext() , R.layout.item_order_course , courseList){
//        @Override
//        protected void convert(ViewHolder holder, final OrderResult.Order data, int position) {
//            final TextView waitTimeTv = (TextView)holder.getView(R.id.waitTimeTv);
//            ImageView lookingTeacherIv = (ImageView)holder.getView(R.id.lookingTeacherIv);
//            CourseInfoView courseInfoView = (CourseInfoView)holder.getView(R.id.courseInfoView);
//            TextView orderedNumTv =  (TextView)holder.getView(R.id.orderedNumTv);
//            RelativeLayout orderedLayout = holder.getView(R.id.orderedLayout);
//
//            //计时器
//            final Handler startTimehandler = new Handler(){
//                public void handleMessage(android.os.Message msg) {
//                    if (null != waitTimeTv) {
//                        waitTimeTv.setText((String) msg.obj);
//                    }
//                }
//            };
//            new Timer("计时器").scheduleAtFixedRate(new TimerTask() {
//                @Override
//                public void run() {
//                    int time = (int)((new Date().getTime() - data.getCreateTime()) / 1000);
//                    String timeFormat;
//                    String min = new DecimalFormat("00").format(time / 60);
//                    if (Integer.parseInt(min) < 60){
//                        String mm = new DecimalFormat("00").format(time / 60);
//                        String ss = new DecimalFormat("00").format(time % 60);
//                        timeFormat = new String( mm + ":" + ss);
//                    }else{
//                        String hh = new DecimalFormat("00").format(time / 3600);
//                        String mm = new DecimalFormat("00").format(time % 3600 / 60);
//                        String ss = new DecimalFormat("00").format(time % 60);
//                        timeFormat = new String( hh + ":" + mm + ":" + ss);
//                    }
//                    Message msg = new Message();
//                    msg.obj = timeFormat;
//                    startTimehandler.sendMessage(msg);
//                }
//
//            }, 0, 1000L);
//
//            //老师图片暂定
//            ImageUtil.loadCircleImage(getContext() , R.mipmap.iv_teacher_test , lookingTeacherIv);
//
//            CourseInfoView.CourseInfoData courseInfoData = new CourseInfoView.CourseInfoData();
//            courseInfoData.setContent(data.getQuestionIntroduction());
//            List<Member> memberList = new ArrayList<>();
//            memberList.clear();
//            memberList.addAll(data.getMemberList());
//            courseInfoData.setMemberList(memberList);
//
//            List<String> imgList = new ArrayList<>();
//            if (!Validators.isEmpty(data.getQuestionImages())){
//                String[] imgs = data.getQuestionImages().split(",");
//                for (int i = 0 ; i < imgs.length ; i++){
//                    imgList.add(imgs[i]);
//                }
//            }
//            courseInfoData.setImgList(imgList);
//            courseInfoView.bindData(courseInfoData);
//
//            orderedNumTv.setText("已接单(" + data.getApplyTeacherCount() + ")");
//
//            orderedLayout.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    OrderedTeacherListActivity.startTeacherListActivity(getActivity() , data.getId() , data.getInitiatorId());
//                }
//            });
//        }
//
//    });
}
